在使用ViewBinding时,如何在RecyclerView中突出显示单击的项目?

您所在的位置:网站首页 recyclerview stableid作用 在使用ViewBinding时,如何在RecyclerView中突出显示单击的项目?

在使用ViewBinding时,如何在RecyclerView中突出显示单击的项目?

2023-05-20 18:50| 来源: 网络整理| 查看: 265

我已经在几篇文章中看到了对这个问题的一种回答,但由于某种原因,这似乎对我不起作用。下面是我的代码:

public class ScheduleAdapter extends RecyclerView.Adapter { private Context context; private ListitemScheduleBinding binding; private Util util; private List scheduleItems; private ItemClickListener itemClickListener; private int selectedPosition = RecyclerView.NO_POSITION; public ScheduleAdapter(Context context, List scheduleItems) { this.context = context; this.scheduleItems = scheduleItems; util = new Util(); } @NonNull @Override public ScheduleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { binding = ListitemScheduleBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false); return new ScheduleViewHolder(binding.getRoot()); } @Override public void onBindViewHolder(@NonNull ScheduleViewHolder holder, int position) { if (selectedPosition == position) { binding.cardView.setCardBackgroundColor(Color.BLACK); } else { binding.cardView.setCardBackgroundColor(Color.GRAY); } binding.cardView.setOnClickListener(v -> { if(selectedPosition == position) { selectedPosition = RecyclerView.NO_POSITION; notifyDataSetChanged(); return; } selectedPosition = position; notifyDataSetChanged(); }); TimeSlot scheduleItem = scheduleItems.get(position); String[] dateSplit = scheduleItem.getDate().split("-"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, Integer.parseInt(dateSplit[0])); calendar.set(Calendar.MONTH, (Integer.parseInt(dateSplit[1]) - 1)); calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateSplit[2])); binding.day.setText(util.getDayNameFromInt(calendar.get(Calendar.DAY_OF_WEEK))); binding.date.setText(String.format(Locale.getDefault(), "%s %s", dateSplit[2], util.getMonthShortNameFromInt(calendar.get(Calendar.MONTH)))); binding.slot.setText(scheduleItem.getTitle()); } @Override public int getItemCount() { return scheduleItems.size(); } public class ScheduleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ScheduleViewHolder(@NonNull View itemView) { super(itemView); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (itemClickListener != null) { itemClickListener.onItemClick(view, getAdapterPosition()); } } } public void setClickListener(ItemClickListener clickListener) { this.itemClickListener = clickListener; } public interface ItemClickListener { void onItemClick(View view, int position); }

}

可以看到,我已经在堆栈上实现了here和其他各种问题中提到的答案。

但是,当我单击列表中的一项时,它要么不会突出显示,要么会突出显示另一项,而不是我单击的那一项。有时,单击的项的内容会更改为列表中另一个项的内容。

我做错了什么?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3